<template>
    <el-menu :default-active="activeMenu" mode="horizontal" @select="handleSelect">
        <template v-for="(item, index) in topMenus">
            <el-menu-item v-if="index < visibleNumber" :key="index" :index="item.path" :style="{ '--theme': theme }">
                <svg-icon :icon-class="item.meta.icon" />
                {{ item.meta.title }}
            </el-menu-item>
        </template>

        <!-- 顶部菜单超出数量折叠 -->
        <el-sub-menu v-if="topMenus.length > visibleNumber" :style="{ '--theme': theme }" index="more">
            <template slot="title">更多菜单</template>
            <template v-for="(item, index) in topMenus">
                <el-menu-item v-if="index >= visibleNumber" :key="index" :index="item.path">
                    <svg-icon :icon-class="item.meta.icon" />
                    {{ item.meta.title }}
                </el-menu-item>
            </template>
        </el-sub-menu>
    </el-menu>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import { constantRoutes } from "@/router";
import { useAppStore } from "@/store/modules/app";
import { usePermissionStoreHook } from "@/store/modules/permission"
import { useSettingsStore } from "@/store/modules/settings"
// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile'];
const route: any = useRoute()
const router = useRouter()
const appStore = useAppStore();
const usePermissionStore = usePermissionStoreHook()
const settingsStore = useSettingsStore();
// 顶部栏初始数
let visibleNumber = ref(5)
// 当前激活菜单的 index
let currentIndex = ref(0)


onBeforeMount(() => {
    window.addEventListener('resize', setVisibleNumber)
})
onBeforeUnmount(() => {
    window.removeEventListener('resize', setVisibleNumber)
})
onMounted(() => {
    setVisibleNumber()
    getRouters()
})

let theme = computed(() => {
    return settingsStore.theme
})

const getRouters = (() => {
    return usePermissionStore.topbarRouters;
})

// 所有的路由信息
let routers: any = computed(() => {
    getRouters()
})

// 顶部显示菜单
let topMenus = computed(() => {
    let topMenus: any = [];
    routers.map((menu) => {
        if (menu.hidden !== true) {
            // 兼容顶部栏一级菜单内部跳转
            if (menu.path === "/") {
                topMenus.push(menu.children[0]);
            } else {
                topMenus.push(menu);
            }
        }
    });
    return topMenus;
})

// 设置子路由
let childrenMenus: any = computed(() => {
    let childrenMenus: any = [];
    routers.map((router) => {
        for (let item in router.children) {
            if (router.children[item].parentPath === undefined) {
                if (router.path === "/") {
                    router.children[item].path = "/" + router.children[item].path;
                } else {
                    if (!ishttp(router.children[item].path)) {
                        router.children[item].path = router.path + "/" + router.children[item].path;
                    }
                }
                router.children[item].parentPath = router.path;
            }
            childrenMenus.push(router.children[item]);
        }
    });
    return constantRoutes.concat(childrenMenus);
})

// 默认激活的菜单
let activeMenu = computed(() => {
    const path = route.path;
    let activePath = path;
    if (path !== undefined && path.lastIndexOf("/") > 0 && hideList.indexOf(path) === -1) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
        appStore.toggleSideBarHide(false);
    } else if (!route.children) {
        activePath = path;
        appStore.toggleSideBarHide(true);
    }
    activeRoutes(activePath);
    return activePath;
})

// 根据宽度计算设置显示栏数
const setVisibleNumber = () => {
    const width: number = document.body.getBoundingClientRect().width / 3;
    visibleNumber.value = width / 85
}
// 菜单选择事件
const handleSelect = (key) => {
    currentIndex.value = key;
    const route = routers.find(item => item.path === key);
    if (ishttp(key)) {
        // http(s):// 路径新窗口打开
        window.open(key, "_blank");
    } else if (!route || !route.children) {
        // 没有子路由路径内部打开
        router.push({ path: key });
        appStore.toggleSideBarHide(true);
    } else {
        // 显示左侧联动菜单
        activeRoutes(key);
        appStore.toggleSideBarHide(false);
    }
}
// 当前激活的路由
const activeRoutes = (key) => {
    let routes: any = [];
    if (childrenMenus && childrenMenus.length > 0) {
        childrenMenus.map((item) => {
            if (key == item.parentPath || (key == "index" && "" == item.path)) {
                routes.push(item);
            }
        });
    }
    if (routes.length > 0) {
        usePermissionStore.SET_SIDEBAR_ROUTERS(routes);
    }
}
const ishttp = (url) => {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}
</script>
<script lang="ts">


export default {
    name: 'TopNav',

    beforeMount() {
        window.addEventListener('resize', this.setVisibleNumber)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setVisibleNumber)
    },
    mounted() {
        this.setVisibleNumber();
    },
    methods: {
        // 根据宽度计算设置显示栏数
        setVisibleNumber() {
            const width = document.body.getBoundingClientRect().width / 3;
            visibleNumber.value = width / 85
        },
        // 菜单选择事件
        handleSelect(key) {
            currentIndex.value = key;
            const route = routers.find(item => item.path === key);
            if (this.ishttp(key)) {
                // http(s):// 路径新窗口打开
                window.open(key, "_blank");
            } else if (!route || !route.children) {
                // 没有子路由路径内部打开
                router.push({ path: key });
                appStore.toggleSideBarHide(true)
            } else {
                // 显示左侧联动菜单
                this.activeRoutes(key);
                appStore.toggleSideBarHide(false)
            }
        },
        // 当前激活的路由
        activeRoutes(key) {
            let routes: any = [];
            if (childrenMenus && childrenMenus.length > 0) {
                childrenMenus.map((item) => {
                    if (key == item.parentPath || (key == "index" && "" == item.path)) {
                        routes.push(item);
                    }
                });
            }
            if (routes.length > 0) {
                usePermissionStore.SET_SIDEBAR_ROUTERS(routes);
            }
        },
        ishttp(url) {
            return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
        }
    },
};
</script>

<style lang="scss">
.topmenu-container.el-menu--horizontal>.el-menu-item {
    float: left;
    height: 50px !important;
    line-height: 50px !important;
    color: #999093 !important;
    padding: 0 5px !important;
    margin: 0 10px !important;
}

.topmenu-container.el-menu--horizontal>.el-menu-item.is-active,
.el-menu--horizontal>.el-submenu.is-active .el-submenu__title {
    border-bottom: 2px solid #{'var(--theme)'} !important;
    color: #303133;
}

/* submenu item */
.topmenu-container.el-menu--horizontal>.el-submenu .el-submenu__title {
    float: left;
    height: 50px !important;
    line-height: 50px !important;
    color: #999093 !important;
    padding: 0 5px !important;
    margin: 0 10px !important;
}
</style>
